<template>
	<wd-toast />
	<BpmComponent :processInstanceId="processInstanceId" @success="refreshDetail">
		<template #approval-info>
			<up-form labelPosition="left" labelWidth="140" v-if="Object.keys(formData).length > 0">
				<up-form-item v-for="field in formFields" :key="field.key" :label="field.label" borderBottom>
					<!-- 如果是附件 -->
					<view v-if="field.isDocument && formData[field.key]" class="file-actions">


						<template v-if="field.isArray">
							<template v-if="(formData[field.key] || []).length > 0">
								<view v-for="(item, idx) in formData[field.key]" :key="idx" class="file-item">
									<text class="file-link" @click="previewFile(item, formData[field.name]?.[idx])">
										{{ getFileName(formData[field.name]?.[idx]) || '无' }}
									</text>
								</view>
							</template>
							<template v-else>
								<text class="file-empty">无</text>
							</template>
						</template>

						<!-- 如果不是数组 -->
						<template v-else>
							<text class="file-link" @click="previewFile(formData[field.key], formData[field.name])">
								{{ getFileName(formData[field.key]) || '无' }}
							</text>
						</template>



					</view>

					<!-- 普通字段 -->
					<text v-else>
						{{ field.format ? field.format(formData[field.key]) : formData[field.key] || '无' }}
					</text>
				</up-form-item>
			</up-form>
		</template>
	</BpmComponent>
</template>

<script setup lang="ts">
import { onLoad } from "@dcloudio/uni-app";
import { ref, unref, reactive, nextTick, getCurrentInstance } from 'vue'
import { DICT_TYPE, getDictLabel } from '@/utils/dict'
import BpmComponent from '@/components/processInstance/detail/index.vue'
import { SealManagerApi, SealManagerVO } from '@/api/oa/sealmanager'
import * as UserApi from '@/api/system/user/index'
import { useMessage, useToast } from 'wot-design-uni'
import { formatDate } from '@/utils/formatTime'
import { getFileName, parseArrayField, previewFile } from '@/utils/fileUtils'

const message = useMessage()
const toast = useToast()

const processInstanceId = ref(null)// 流程实例的编号
const detailId = ref(null)
const formData = ref<SealManagerVO>({} as any)
const sealList = ref<any[]>([]) // 印章列表
const userList = ref<any[]>([])
// const formFields = [
// {
// 	label: '类型', key: 'type', format: (val : any) => {
// 		return getDictLabel(DICT_TYPE.OA_OUT_TYPE, val)
// 	}
// },
// 	{ label: '标题', key: 'title' },
// 	{ label: '主送', key: 'mainRecipient' },
// 	{ label: '抄送', key: 'ccSend' },
// 	{ label: '发文字号', key: 'proofreader' },
// 	{ label: '校对人', key: 'contractAmount' },
// 	{ label: '印份数', key: 'totalPrinted' },
// 	{ label: '正文', key: 'eids', isDocument: true },

// ]
const formFields = [
	{ label: '文件名称', key: 'fileName' },
	{ label: '申请部门', key: 'applicationDept' },
	{ label: '申请人', key: 'applicantName' },
	{ label: '申请日期', key: 'applicationDate', format: formatDate },
	{

		label: '印章名称', key: 'sealId', format: (val: any) => {
			if (!val) return '-'
			const ids = String(val).split(',').map(id => Number(id.trim()))

			const names = ids
				.map(id => sealList.value.find(item => item.id === id)?.sealName)
				.filter(Boolean) // 过滤掉没找到的
			return names.length ? names.join(', ') : '-'
		}

	},
	{ label: '事由', key: 'reason' },

	{ label: '报送部门', key: 'submitDept' },
	{

		label: '是否请示主管领导', key: 'directorConsulted', format: (val: any) => {
			return val === '0' ? '是' : '否'
		}

	},
	{ label: '附件', key: 'attachment', isDocument: true, name: 'ename' },

]

/** 获取用户列表 */
const getUserList = async () => {
	try {
		userList.value = await UserApi.getSimpleUserList();
	} catch (error) {
		console.error("获取用户列表失败:", error);
		userList.value = []; // 失败时，防止 userOptions.value 变成 undefined
	}
}

onLoad(async (options) => {
	processInstanceId.value = options?.processInstanceId
	detailId.value = options?.id
	/** 获得详情 */
	await getUserList()
	getDetailById()
	getSealList()

})
const getSealList = async () => {
	// 获取印章列表
	try {
		const params = { pageNo: 1, pageSize: 100 }
		const result = await SealManagerApi.getSealList(params)
		sealList.value = result.list || []
	} catch (error) {
		toast.error('获取印章列表失败')
	}
}
const refreshDetail = () => {
	console.log('父组件收到刷新事件，重新加载数据')
	getDetailById() // 调用父组件自己的获取详情方法
}
/** 获取页面详情 */
const getDetailById = async () => {
	try {
		const data = await SealManagerApi.getSealManager(Number(detailId.value))
		formData.value = data
		if (formData.value.applicantId) {
			const selected = userList.value.find(item => item.id === formData.value.applicantId)
			console.log('selected', selected);

			formData.value.applicantName = selected.nickname
		}
	} catch (error) {
		console.log('加载数据失败')
	}
}
</script>

<style>
/* 样式 */
/* 新增文件链接样式 */
.file-link {
	color: #007AFF;
	text-decoration: underline;
	cursor: pointer;
}

.uv-node {
	height: 34rpx;
	width: 34rpx;
	border-radius: 50%;
	background-color: #ddd;
	display: flex;
	align-items: center;
	justify-content: center;
	color: #fff;
	flex-shrink: 0;
	z-index: -1;
}

.audit-node {
	margin: 5px 0;
}
</style>